/* * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.mobile.mobileinfo.slice;

import com.mobile.mobilehardware.utils.Logs;
import com.mobile.mobilehardware.wifilist.WifiHelper;
import com.mobile.mobilehardware.wifilist.WifiScanListener;
import com.mobile.mobileinfo.ResourceTable;
import com.mobile.mobileinfo.data.Param;
import com.mobile.mobileinfo.view.adapter.PageViewAdapter;
import com.mobile.mobileinfo.view.model.Constants;
import com.mobile.mobileinfo.view.page.AbstractPageView;
import com.mobile.mobileinfo.view.page.AppInfo;
import com.mobile.mobileinfo.view.page.AudioInfo;
import com.mobile.mobileinfo.view.page.BandInfo;
import com.mobile.mobileinfo.view.page.BatteryInfo;
import com.mobile.mobileinfo.view.page.BluetoothInfo;
import com.mobile.mobileinfo.view.page.BuildInfo;
import com.mobile.mobileinfo.view.page.CameraInfo;
import com.mobile.mobileinfo.view.page.CpuInfo;
import com.mobile.mobileinfo.view.page.DebugInfo;
import com.mobile.mobileinfo.view.page.EmulatorInfo;
import com.mobile.mobileinfo.view.page.HookInfo;
import com.mobile.mobileinfo.view.page.IDInfo;
import com.mobile.mobileinfo.view.page.LocalInfo;
import com.mobile.mobileinfo.view.page.MemoryInfo;
import com.mobile.mobileinfo.view.page.MoreOpenInfo;
import com.mobile.mobileinfo.view.page.NetWorkInfo;
import com.mobile.mobileinfo.view.page.RandomInfo;
import com.mobile.mobileinfo.view.page.RootInfo;
import com.mobile.mobileinfo.view.page.SDcardInfo;
import com.mobile.mobileinfo.view.page.ScreenInfo;
import com.mobile.mobileinfo.view.page.SettingInfo;
import com.mobile.mobileinfo.view.page.SignalInfo;
import com.mobile.mobileinfo.view.page.SimCardInfo;
import com.mobile.mobileinfo.view.page.UAInfo;
import com.mobile.mobileinfo.view.page.WifiListInfo;
import com.mobile.mobileinfo.view.tab.TabListListener;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.PageSlider;
import ohos.agp.components.TabList;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Color;
import ohos.agp.utils.TextAlignment;
import ohos.agp.window.service.DisplayAttributes;
import ohos.agp.window.service.DisplayManager;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.eventhandler.InnerEvent;
import ohos.utils.zson.ZSONObject;

import java.util.ArrayList;
import java.util.List;

import static com.mobile.mobileinfo.data.ZsonExtract.getListParam;


/**
 * The type Sample tabs default slice.
 */
public class MainAbilitySlice extends AbilitySlice {
    private DirectionalLayout mRootComponentDL;
    private static PageSlider mPager;
    private static TabList mTopTabList;
    private TabList mSubTabList;
    private PageViewAdapter pageViewAdapter;
    private static Boolean mWifiValUpdated = false;
    private static Boolean mWifiScanStarted = false;

    private static List<AbstractPageView> mPageViews = new ArrayList<>();
    private final String[] TopTabTexts = {"SAFE", "APP", "NET", "PHONE", "UNIQUEID"};
    private static final String[] PageSAFEFeatures = {"DEBUG", "EMULATOR", "HOOK", "MOREOPEN", "ROOT"};
    private static final String[] PageAPPFeatures = {"APP"};
    private static final String[] PageNETFeatures = {"NETWORK", "SIGNAL", "SIMCARD", "WIFILIST"};
    private static final String[] PagePHONEFeatures = {"RANDOM", "AUDIO", "BAND", "BATTERY", "BLUETOOTH", "BUILD", "CAMERA", "CPU", "LOCAL", "MEMORY", "SCREEN", "SDCARD", "SETTING", "UA"};
    private static final String[] PageUNIQUEIDFeatures = {"PHONEID"};
    private static final String[][] mSubTabTexts = {PageSAFEFeatures, PageAPPFeatures, PageNETFeatures, PagePHONEFeatures, PageUNIQUEIDFeatures};

    public static EventHandler eventHandler = new EventHandler(EventRunner.getMainEventRunner()) {
        @Override
        protected void processEvent(InnerEvent event) {
            super.processEvent(event);
            switch (event.eventId) {
                case Constants.WIFIINFO_TASK:
                    if (!mWifiScanStarted) {
                        mWifiScanStarted = true;
                        WifiHelper.wifiList(new WifiScanListener() {
                            @Override
                            public void onResult(ZSONObject jsonObject) {
                                WifiListInfo.setList((ArrayList<Param>) getListParam(jsonObject));
                                mWifiScanStarted = false;
                                mWifiValUpdated = true;
                                if (mTopTabList.getSelectedTabIndex() == 2) {
                                    refreshPageList();
                                }
                            }
                        });
                    }
                    break;
            }
        }
    };

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        ComponentContainer componentContainer = (ComponentContainer) LayoutScatter.getInstance(this).parse
                (ResourceTable.Layout_slice_slider_tabs, null, false);
        if (componentContainer instanceof ComponentContainer) {
            mRootComponentDL = (DirectionalLayout) componentContainer.findComponentById(ResourceTable.Id_dlRootLayout);
            mPager = (PageSlider) componentContainer.findComponentById(ResourceTable.Id_slider);
            mTopTabList = (TabList) componentContainer.findComponentById(ResourceTable.Id_TopTabList);
            mSubTabList = (TabList) componentContainer.findComponentById(ResourceTable.Id_SubTabList);
            initPageView();
            initTopTabs();
            initSubTabs();
            setUIContent(componentContainer);
        }
    }

    private void initPageView() {
        initPager();
        mPager.setOrientation(Component.HORIZONTAL);
        mPager.setSlidingPossible(true);
        mPager.addPageChangedListener(new PageSlider.PageChangedListener() {
            @Override
            public void onPageSliding(int itemPos, float itemPosOffset, int itemPosOffsetPixels) {
            }

            @Override
            public void onPageSlideStateChanged(int state) {
            }

            @Override
            public void onPageChosen(int position) {
                mSubTabList.selectTab(mSubTabList.getTabAt(position));
            }
        });
    }

    private void initTopTabs() {
        mTopTabList.setTabTextSize(46);
        mTopTabList.setTabLength(260);
        mTopTabList.setOrientation(Component.HORIZONTAL);
        mTopTabList.setBackground(new ShapeElement(getContext(), ResourceTable.Graphic_background_ability_main));
        mTopTabList.setCentralScrollMode(true);
        mTopTabList.setTabTextAlignment(TextAlignment.CENTER);
        mTopTabList.setTabTextColors(new Color(0xffff8800).getValue(), new Color(0xff669900).getValue());
        for (String next : TopTabTexts) {
            TabList.Tab tab = new TabList(this).new Tab(this);
            tab.setFocusable(Component.FOCUS_ENABLE);
            tab.setText(next);
            tab.setTextColor(Color.YELLOW);
            tab.setTextAlignment(TextAlignment.CENTER);
            mTopTabList.addTab(tab);
        }
        mTopTabList.setFixedMode(false);
        mTopTabList.selectTab(mTopTabList.getTabAt(0));
        mTopTabList.addTabSelectedListener(new TabList.TabSelectedListener() {
            @Override
            public void onSelected(TabList.Tab tab) {
                int tabcount = mSubTabList.getTabCount();
                while (tabcount != 0) {
                    mSubTabList.removeTab(0);
                    tabcount--;
                }
                resetSubTabs();
                resetPageList();
                autoScroll(0);
                if (mWifiValUpdated && (tab.getPosition() != 2)) {
                    WifiListInfo.setList(null);
                    mWifiValUpdated = false;
                }
            }

            @Override
            public void onUnselected(TabList.Tab tab) {
            }

            @Override
            public void onReselected(TabList.Tab tab) {

            }
        });
    }

    private void initSubTabs() {
        mSubTabList.setTabTextSize(46);
        mSubTabList.setTabLength(260);
        mSubTabList.setOrientation(Component.HORIZONTAL);
        mSubTabList.setCentralScrollMode(true);
        mSubTabList.setBackground(new ShapeElement(getContext(), ResourceTable.Graphic_background_ability_main));
        mSubTabList.setTabTextAlignment(TextAlignment.CENTER);
        mSubTabList.setTabTextColors(new Color(0xffff8800).getValue(), new Color(0xff669900).getValue());
        resetSubTabs();
        mSubTabList.addTabSelectedListener(new TabListListener(this, mPageViews, mPager));
        mSubTabList.setFixedMode(false);
        mSubTabList.selectTab(mSubTabList.getTabAt(0));

        DisplayAttributes displayAttributes = DisplayManager.getInstance().getDefaultDisplay
                (getContext()).get().getAttributes();
        mScreenWidth = displayAttributes.width;
    }

    private static final int INTERVAL_POSITION = 2;
    private int mLastPosition = -1;
    private float mScreenWidth;
    private int mTabPadding = 80;
    private void autoScroll(int position) {
        int count = mSubTabList.getTabCount();
        float scrollX;
        int advancePosition;

        if (position >= mLastPosition) {
            if (position >= (count - 1) - INTERVAL_POSITION) {
                advancePosition = count - 1;
            } else {
                advancePosition = position + INTERVAL_POSITION;
            }

            int advanceX = mSubTabList.getTabAt(advancePosition).getLocationOnScreen()[0];
            int advanceWidth = mSubTabList.getTabAt(advancePosition).getPaddingLeft()
                    + mSubTabList.getTabAt(advancePosition).getWidth() + mSubTabList.getTabAt(advancePosition).getPaddingRight() + mTabPadding;

            if (advanceX + advanceWidth > mScreenWidth) {
                scrollX = advanceX + advanceWidth - mScreenWidth;
            } else {
                scrollX = 0;
            }
        } else {
            if (position <= INTERVAL_POSITION) {
                advancePosition = 0;
            } else {
                advancePosition = position - INTERVAL_POSITION;
            }

            int advanceX = mSubTabList.getTabAt(advancePosition).getLocationOnScreen()[0];
            scrollX = Math.min(0, advanceX - mTabPadding);
        }
        this.mLastPosition = position;

        if (scrollX == 0) {
            return;
        }
        mSubTabList.fluentScrollByX((int) scrollX);
    }

    private void resetSubTabs() {
        int tabselect = mTopTabList.getSelectedTabIndex();
        if (tabselect == -1) {
            tabselect = 0;
        }
        Logs.d("", "getSelectedTabIndex = " + mTopTabList.getSelectedTabIndex());
        for (String next : mSubTabTexts[tabselect]) {
            TabList.Tab tab = new TabList(this).new Tab(this);
            tab.setFocusable(Component.FOCUS_ENABLE);
            tab.setText(next);
            tab.setTextAlignment(TextAlignment.CENTER);
            mSubTabList.addTab(tab);
        }
        mSubTabList.selectTab(mSubTabList.getTabAt(0));
        mSubTabList.invalidate();
    }

    private void initPager() {
        resetPageList();
        pageViewAdapter.setWindow(getWindow());
        mPager.setOrientation(Component.HORIZONTAL);
        mPager.setSlidingPossible(true);
        mPager.addPageChangedListener(new PageSlider.PageChangedListener() {
            @Override
            public void onPageSliding(int val, float floval, int value) {
                // Do something
            }

            @Override
            public void onPageSlideStateChanged(int val) {
            }

            @Override
            public void onPageChosen(int position) {
                mSubTabList.selectTab(mSubTabList.getTabAt(position));
                autoScroll(position);
            }
        });
    }

    private void resetPageList() {
        int subtabindex = mTopTabList.getSelectedTabIndex();
        mPageViews.clear();
        if (subtabindex == -1)
            subtabindex = 0;
        for (String pagetitle : mSubTabTexts[subtabindex]) {
            mPageViews.add(getInfoObject(pagetitle));
        }
        pageViewAdapter = new PageViewAdapter(mPageViews);
        mPager.setProvider(pageViewAdapter);
        mPager.setCurrentPage(0);
        mPager.invalidate();
    }

    private static void refreshPageList() {
        int currentPage = mPager.getCurrentPage();
        int subtabindex = mTopTabList.getSelectedTabIndex();
        mPageViews.clear();
        if (subtabindex == -1)
            subtabindex = 0;
        for (String pagetitle : mSubTabTexts[subtabindex]) {
            mPageViews.add(getInfoObject(pagetitle));
        }
        PageViewAdapter pageViewAdapter = new PageViewAdapter(mPageViews);
        mPager.setProvider(pageViewAdapter);
        mPager.setCurrentPage(currentPage);
        mPager.invalidate();
    }

    private static AbstractPageView getInfoObject(String type) {
        switch (type) {
            case "DEBUG":
                return new DebugInfo();
            case "EMULATOR":
                return new EmulatorInfo();
            case "HOOK":
                return new HookInfo();
            case "MOREOPEN":
                return new MoreOpenInfo();
            case "ROOT":
                return new RootInfo();
            case "APP":
                return new AppInfo();
            case "APPLIST":
                return new AppInfo();
            case "NETWORK":
                return new NetWorkInfo();
            case "SIGNAL":
                return new SignalInfo();
            case "SIMCARD":
                return new SimCardInfo();
            case "WIFILIST":
                return new WifiListInfo();
            case "RANDOM":
                return new RandomInfo();
            case "AUDIO":
                return new AudioInfo();
            case "BAND":
                return new BandInfo();
            case "BATTERY":
                return new BatteryInfo();
            case "BLUETOOTH":
                return new BluetoothInfo();
            case "BUILD":
                return new BuildInfo();
            case "CAMERA":
                return new CameraInfo();
            case "CPU":
                return new CpuInfo();
            case "LOCAL":
                return new LocalInfo();
            case "MEMORY":
                return new MemoryInfo();
            case "SCREEN":
                return new ScreenInfo();
            case "SDCARD":
                return new SDcardInfo();
            case "SETTING":
                return new SettingInfo();
            case "UA":
                return new UAInfo();
            case "PHONEID":
                return new IDInfo();
            default:
                break;
        }
        return null;
    }

    @Override
    protected void onStop() {
        pageViewAdapter.setWindow(null);
        super.onStop();
    }
}